<template>
  <div class="page_content daraBoardStreetAnalysis_content">
    <div class="header_box p-12 bold flex flex-ac flex-jsb">
      <div class="title flex flex-ac">
        <div class="mr-30">用户列表</div>
        <!-- <el-button
          @click="handleAddClick"
          type="success"
          size="small"
          :icon="View"
          >详情</el-button
        > -->
      </div>
      <div class="flex flex-ac">
        <el-button @click="handleAllDetailsClick" type="success" size="small" :icon="View" class="mr-10">
          详情
        </el-button>
        <!-- <el-icon class="add_icon" :size="20" @click="handleAddClick">
            <CirclePlus />
          </el-icon> -->
        <!-- <el-button @click="handleAddClick" type="primary" size="small" :icon="Plus">新增</el-button> -->
        <div class="dots flex flex-c flex-jc flex-ac">
          <span>.</span>
          <span>.</span>
          <span>.</span>
        </div>
      </div>
    </div>
    <div class="main_box m-10 grid">
      <el-table ref="singleTable" :data="tableData" max-height="340" style="width: 100%" fit :header-cell-style="{
          color: '#000',
          background: '#f2f2f2',
        }" tooltip-effect="light">
        <el-table-column type="index" label="序号" align="center" width="55">
        </el-table-column>
        <el-table-column prop="uname" label="用户名称" align="center" width="95">
        </el-table-column>
        <el-table-column prop="createTime" label="申请时间" align="center">
          <template #default="scope">
            <div>{{ formatDate(scope.row.createTime) }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="userName" label="审核状态" align="center">
          <template #default="scope">
            <div v-if="scope.row.activation == 0">未注册</div>
            <div v-else-if="scope.row.activation == 1">待审批</div>
            <div v-else-if="scope.row.activation == 2">已激活</div>
            <div v-else-if="scope.row.activation == 3">驳回</div>
          </template>
        </el-table-column>
        <el-table-column prop="account" label="微信号" align="center">
        </el-table-column>
        <el-table-column prop="phoneNumber" label="联系方式" align="center">
        </el-table-column>
        <el-table-column prop="userRights" label="角色管理" align="center" :show-overflow-tooltip="true">
        </el-table-column>

        <el-table-column prop="default" label="操作" width="200" fixed="right" align="center">
          <template #default="scope">
            <el-button @click="handleDetailsClick(scope.row)" type="success" size="small">
              详情
            </el-button>
            <el-button @click="handleEditClick(scope.row)" type="primary" size="small">编辑</el-button>
            <el-popconfirm width="220" :icon="WarningFilled" icon-color="#f56c6c" title="是否确认删除"
              confirm-button-type="danger" @confirm="handleDelClick(scope.row)" placement="top"
              cancel-button-type="primary" confirm-button-text="确定" cancel-button-text="取消">
              <template #reference>
                <!-- @click="handleDelClick(scope.row)" -->
                <el-button type="danger" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog title="用户详情" v-model="dialogVisible" width="80%" draggable align-center destroy-on-close
      :before-close="handleClose">
      <el-form :model="form" label-width="80px" class="flex">
        <div class="border_shu"></div>
        <el-form-item label="用户名称">
          <el-input v-model="form.data.username" maxlength="20" placeholder="请输入搜索关键词，例如：张三" clearable
            style="width: 240px"></el-input>
        </el-form-item>
      </el-form>
      <el-table ref="singleTable" :data="tableAllData" height="340" max-height="340" style="width: 100%" fit
        :header-cell-style="{
          color: '#000',
          background: '#f2f2f2',
        }">
        <el-table-column type="index" label="序号" align="center" width="55">
        </el-table-column>
        <el-table-column prop="uname" label="用户名称" align="center" width="95">
        </el-table-column>
        <el-table-column prop="createTime" label="申请时间" align="center">
          <template #default="scope">
            <div>{{ formatDate(scope.row.createTime) }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="userName" label="审核状态" align="center">
          <template #default="scope">
            <div v-if="scope.row.activation == 0">未注册</div>
            <div v-else-if="scope.row.activation == 1">待审批</div>
            <div v-else-if="scope.row.activation == 2">已激活</div>
            <div v-else-if="scope.row.activation == 3">驳回</div>
          </template>
        </el-table-column>
        <el-table-column prop="account" label="微信号" align="center">
        </el-table-column>
        <el-table-column prop="phoneNumber" label="联系方式" align="center">
        </el-table-column>
        <el-table-column prop="userRights" label="角色管理" align="center" :show-overflow-tooltip="true">
        </el-table-column>

        <el-table-column prop="default" label="操作" width="200" fixed="right" align="center">
          <template #default="scope">
            <el-button @click="handleDetailsClick(scope.row)" type="success" size="small">
              详情
            </el-button>
            <el-button @click="handleEditClick(scope.row)" type="primary" size="small">编辑</el-button>
            <el-popconfirm width="220" :icon="WarningFilled" icon-color="#f56c6c" title="是否确认删除"
              confirm-button-type="danger" @confirm="handleDelClick(scope.row)" placement="top"
              cancel-button-type="primary" confirm-button-text="确定" cancel-button-text="取消">
              <template #reference>
                <!-- @click="handleDelClick(scope.row)" -->
                <el-button type="danger" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination_box mt-20">
        <el-pagination small :current-page.sync="currentPage" :page-size.sync="pageSize" :page-sizes="[10, 20, 30, 50]"
          background layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </el-dialog>
    <!-- 编辑 -->
    <el-dialog title="信息详情" v-model="dialogAddVisible" width="70%" draggable align-center destroy-on-close
      class="dialog_content" :before-close="handleClose">
      <el-row>
        <el-col class="img-left" :span="8">
          <el-upload class="avatar-uploader" :action="uploadUrl" accept=".jpg,.png,.jpeg" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <el-image v-if="avator" :src="avator" class="avatar" />
            <el-button type="primary">更改头像</el-button>
          </el-upload>
        </el-col>
        <el-col :span="16">
          <el-form :model="detailsForm">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="申请时间">
                  <div>{{ getDetailsForm.createTime }}</div>
                </el-form-item>
                <el-form-item label="审核状态">
                  <div>{{ getDetailsForm.activation == 2 ? "已激活" : "未激活" }}</div>
                </el-form-item>
                <el-form-item label="用户姓名">
                  <el-input v-model="detailsForm.uname" />
                </el-form-item>
                <el-form-item label="手机号码">
                  <el-input v-model="detailsForm.phoneNumber" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="更新时间">
                  <div>{{ getDetailsForm.updateTime }}</div>
                </el-form-item>
                <el-form-item label="微信号">
                  <el-input v-model="detailsForm.account" />
                </el-form-item>
                <el-form-item label="身份证">
                  <el-input v-model="detailsForm.personCard" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="20">
                <el-form-item label="到期日期">
                  <el-date-picker v-model="detailsForm.expireTime" type="date" placeholder="到期日期"
                    clearable></el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="20">
                <el-form-item label="角色管理">
                  <el-select v-model="detailsForm.newRoleId" multiple placeholder="角色管理" collapse-tags
                    style="width: 240px">
                    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-col>
      </el-row>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">保存更改</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import {
  ref,
  watch,
  onMounted,
  onBeforeUnmount,
  reactive,
  onUnmounted,
} from "vue";
// import { useStore } from "vuex";
import { ElMessageBox, ElMessage } from "element-plus";
import type { UploadInstance, UploadProps, UploadRawFile, UploadUserFile } from 'element-plus'
import {
  WarningFilled,
  Plus,
  Delete,
  Edit,
  Search,
  Share,
  Upload,
  View,
} from "@element-plus/icons-vue";
import { getToken } from "@/utils/auth";
// const store = useStore();
import { getRolePermissionsListApi, getUserList, submitUserList, wxUserListApi } from "@/api/resourceManagement";
import { useMousePosition } from "@/hooks/dateSelect";
const { timeType } = useMousePosition();
// const iconPng = new URL("@/assets/img/index/pf.png", import.meta.url).href;
// const props: any = defineProps({});
import { genFileId } from 'element-plus'

const upload = ref<UploadInstance>()

// 编辑获取
let getDetailsForm: any = ref({})
// 编辑提交
let detailsForm: any = ref({})
const options = ref([
  {
    value: 'Option1',
    label: 'Option1',
  },
  {
    value: 'Option2',
    label: 'Option2',
  },
])
const avator = ref();//图片显示

onMounted(() => { });

onBeforeUnmount(() => { });
onUnmounted(() => { });
let dialogVisible = ref(false);
let dialogAddVisible = ref(false);
const radiopzq = ref("3");

let form: any = reactive({
  data: {},
});
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);
let tableData = ref([]);
let tableAllData = ref([]);
let unitManagement = ref([]);
let selectObj = ref({
  vehicleType: 99,
  key: null,
});
const fileList = ref<UploadUserFile[]>([]);
const uploadHeaders = ref({
  "X-Access-Token": getToken(),
});
watch(
  timeType,
  () => {
    init();
  },
  {
    immediate: true,
  }
);

function init() {
  wxUserList();
}

// 获取角色
async function getRolePermissionsList() {
  options.value = [];
  let info = {
    pageNo: 1,
    pageSize: 999,
  };
  const res = await getRolePermissionsListApi(info);
  console.log(" 用户组 角色权限 三级分类-分页列表查询", res, res?.data);
  if (res?.data?.code != 200) return;
  let { result = {} } = res?.data;
  options.value = result?.records.map((item: any) => {
    return {
      label: item.permissionName, value: item.id
    }
  }) || [];

}
getRolePermissionsList()

// 小程序微信用户-分页列表查询
async function wxUserList() {
  tableData.value = [];
  let info = {
    key: null,
    pageNo: 1,
    pageSize: 8,
    sort: null,
  };
  const res = await wxUserListApi(info);
  console.log("小程序微信用户-分页列表查询", res, res?.data);
  if (res?.data?.code != 200) return;
  let { result = {} } = res?.data;
  let tableDatas = result?.records || [];
  tableData.value = tableDatas.map((item: any) => {
    let userRights: any = [];
    if (item.userRightsList?.length) {
      item.userRightsList.map((el: any) => {
        if (el?.threeName) userRights.push(el.threeName);
      });
    }
    item.userRights = userRights.join(",");
    return { ...item };
  });

  // console.log(
  //   " 用户组 角色权限 三级分类-分页列表查询",
  //   tableData.value,
  //   result
  // );
}
async function wxUserAllList() {
  tableAllData.value = [];
  let info = {
    key: null,
    pageNo: currentPage.value,
    pageSize: pageSize.value,
    sort: null,
  };
  const res = await wxUserListApi(info);
  console.log("小程序微信用户-分页列表查询", res, res?.data);
  if (res?.data?.code != 200) return;
  let { result = {} } = res?.data;
  let tableDatas = result?.records || [];
  tableAllData.value = tableDatas.map((item: any) => {
    let userRights: any = [];
    if (item.userRightsList?.length) {
      item.userRightsList.map((el: any) => {
        if (el?.threeName) userRights.push(el.threeName);
      });
    }
    item.userRights = userRights.join(",");
    return { ...item };
  });

  total.value = Number(result?.total) || 0;
}
const handleRemove: UploadProps["onRemove"] = (file, uploadFiles) => {
  console.log(file, uploadFiles);
  // if (file?.response?.code != 200) {
  //   return ElMessage.warning(file?.response?.message || "操作失败");
  // }
};

const handlePreview: UploadProps["onPreview"] = (uploadFile) => {
  console.log(uploadFile);
};



//可以将userid换成自己的参数
const uploadUrl = ref("/jeecg-boot/fileManage/upload");

const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  avator.value = URL.createObjectURL(uploadFile.raw!);
  console.log(avator.value);

  //更新sessionStorage和vuex
  sessionStorage.setItem("avator", avator.value);
  // store.state.avator = avator.value;
};
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("图片不能超过2MB!");
    return false;
  }
  return true;
};

const handleExceed: UploadProps["onExceed"] = (files, uploadFiles) => {
  ElMessage.warning("只能上传一张图片，如已经上传一张了，请先清除再添加上传");
};

const beforeRemove: UploadProps["beforeRemove"] = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(`是否删除${uploadFile.name} ?`).then(
    () => true,
    () => false
  );
};
// 总的详情
const handleAllDetailsClick = () => {
  dialogVisible.value = true;
  wxUserAllList();
};
// 新增
const handleAddClick = () => {
  dialogVisible.value = true;
};
// 详情
const handleDetailsClick = (row: any) => {
  dialogVisible.value = true;
};
// 打开编辑弹出框
const handleEditClick = async (row: any) => {
  dialogAddVisible.value = true;
  const res: any = await getUserList(row.id)
  // console.log(res.data.result);
  avator.value = res.data.result.headpicUrl
  getDetailsForm.value = res.data.result
  detailsForm.value.account = res.data.result.account
  detailsForm.value.expireTime = res.data.result.expireTime
  detailsForm.value.headpicUrl = res.data.result.headpicUrl
  detailsForm.value.id = res.data.result.id
  detailsForm.value.lastRoleId = res.data.result.lastRoleId
  detailsForm.value.newRoleId = res.data.result.newRoleId
  detailsForm.value.personCard = res.data.result.personCard
  detailsForm.value.phoneNumber = res.data.result.phoneNumber
  detailsForm.value.uname = res.data.result.uname

};
// 关闭
const handleClose = () => {
  dialogVisible.value = false;
  dialogAddVisible.value = false
};
// 删除
const handleDelClick = (row: any) => { };

// 提交编辑
const submitForm = () => {
  ElMessageBox.confirm("确定要提交表单吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      // 处理提交逻辑
      console.log(form.data);
      detailsForm.value.newRoleId = detailsForm.value.newRoleId.toString()

      const res = await submitUserList(detailsForm.value)
      console.log(res);
      ElMessageBox.alert("提交成功", "提示", { type: "success" });
    })
    .catch(() => {
      // 取消提交逻辑
    });
};
const formatDate = (time: any) => {
  try {
    time = time.replace(/-/g, "/");
  } catch (err) { }
  var date = new Date(time);
  var YY = date.getFullYear() + "-";
  var MM =
    (date.getMonth() + 1 < 10
      ? "0" + (date.getMonth() + 1)
      : date.getMonth() + 1) + "-";
  var DD = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
  return YY + MM + DD;
};
//条数
function handleSizeChange(value: any) {
  pageSize.value = value;
  console.log("条数", value);
  wxUserAllList(); //调取接口
}
function handleCurrentChange(value: any) {
  //页码发生变化会触发，这个用来触发点击页码时触发的。
  currentPage.value = value;
  console.log("页码发生变化会触发", value);
  wxUserAllList(); //调取接口
}
</script>

<style lang="scss" scoped>
.img-left {
  display: flex
}

::v-deep(.el-upload) {
  display: block;
}

.daraBoardStreetAnalysis_content {
  height: 400px;

  .header_box {
    .add_icon {
      margin-right: 5px;
      cursor: pointer;
    }
  }

  .main_box {
    overflow-y: auto;
  }

  .el-radio.el-radio--large {
    height: 30px;
  }

  .el-upload__tip {
    font-size: 13px;
    margin-top: -30px;
    margin-left: 100px;
    color: #939191;
  }

  .el-dialog__body {
    padding: 10px 10px !important;
  }

  .border_shu {
    width: 2.2px;
    height: 12px;
    background-color: #0052d9;
    margin-top: 10px;
    border-radius: 4px;
  }
}
</style>